package cn.wu.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.wu.reggie.common.R;
import cn.wu.reggie.entity.*;
import cn.wu.reggie.mapper.*;
import cn.wu.reggie.service.OrderService;
import com.sun.org.apache.bcel.internal.generic.NEW;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private AddressBookMapper addressBookMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ShoppingCartMapper shoppingCartMapper;

    @Override
    @Transactional
    public R save(Orders order) {
        // 0.1 生成订单id 工具类中的id生成器 唯一long值
        Long orderId = IdUtil.getSnowflake().nextId();
        // 0.2 设置总金额初始值
         BigDecimal totalAmount = new BigDecimal(0);

        // A. 获得当前用户id, 查询当前用户的购物车数据
        Long userId = order.getUserId();
        List<ShoppingCart> cartList = shoppingCartMapper.findAllByUserId(userId);

        //B. 根据当前登录用户id, 查询用户数据
        User user = userMapper.findById(userId);

        //C. 根据地址ID, 查询地址数据
        AddressBook address = addressBookMapper.getById(order.getAddressBookId());

        //D. 组装订单明细数据, 批量保存订单明细
        List<OrderDetail> orderDetailList =  new ArrayList<>();

        for (ShoppingCart sc : cartList) {
            //将每个购物项封装成订单详情
            OrderDetail od = new OrderDetail();
            BeanUtils.copyProperties(sc,od);

            // 计算总金额
            totalAmount = totalAmount.add(od.getAmount().multiply(new BigDecimal(od.getNumber())));

            // 设置订单id
            od.setOrderId(orderId);

            orderDetailList.add(od);
        }

        orderDetailMapper.batchSave(orderDetailList);

        //E. 组装订单数据, 批量保存订单数据
        order.setId(orderId);
        order.setNumber(String.valueOf(orderId));
        order.setStatus(1);
        order.setOrderTime(LocalDateTime.now());
        order.setCheckoutTime(LocalDateTime.now());

        // 设置金额
        order.setAmount(totalAmount);

        order.setUserName(user.getName());

        //收货人信息
        order.setPhone(address.getPhone());
        order.setAddress(address.getDetail());
        order.setConsignee(address.getConsignee());

        orderMapper.save(order);

        //F. 删除当前用户的购物车列表数据
        shoppingCartMapper.deleteByUserId(userId);

        return R.success(null);
    }
}
